package vn.com.hung.notetaker.config;

import java.awt.Component;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;

import javax.swing.JFileChooser;

import com.google.common.io.Closeables;
import com.google.common.io.Files;

import vn.com.hung.notetaker.utils.DialogDisplayer;

public class Conf {
    
    private static final String OS = System.getProperty("os.name").toLowerCase();
    public static final String WORKING_DIR = "working.dir";
    public static final String DATABASE_PATH = "database.path";
    public static final String USER_NAME = "username";
    public static final String PWD = "pwd";
    
    private static Map<String, String> confParams = new HashMap<String, String>();
    
    
    public static String getOSName() {
        return OS;
    }
    public static void startUp(Component comp) {
        
        File workspace = new File(Conf.getDefaultWorkingDir());
        File metadata = new File(Conf.getMetadatPath());
        if (!workspace.exists()) {
            if (!workspace.mkdir()) {
                DialogDisplayer.showDefaultErrorDialog("Cannot create workspace");
            }
        }
        if (!metadata.exists()) {
            DialogDisplayer.showDefaultErrorDialog("Metadata not found!\n"
                    + "Choose directory/folder to put your woking data");
            JFileChooser c = new JFileChooser();
            c.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
            c.setDialogTitle("Choose Directory/Folder");
            c.showSaveDialog(comp.getParent());
            String path = c.getSelectedFile().getAbsolutePath();
            set(DATABASE_PATH,path);
            saveMetadata(getInitContext(path));
        } else {
            readMetadata();
        }
       
    }
    
    private static String getInitContext(String dbPath) {
        StringBuilder strBd = new StringBuilder();
        strBd.append(DATABASE_PATH + "::" + dbPath + "\n");
        strBd.append(USER_NAME + "::" + "hung\n");
        strBd.append(PWD + "::" + "9cb2e2b91d100e62f2ab3aeacb270028\n");
        return strBd.toString();
    }
    public static boolean isLinux() {
        return (OS.indexOf("linux") >= 0);
    }
    
    public static boolean isWindow() {
        return (OS.indexOf("win") >=0);
    }
    
    public static void set(String key, String value) {
        confParams.put(key, value);
    }
    
    public static String get(String key) {
        return confParams.get(key);
    }
    
    public static String getDefaultWorkingDir() {
        if (isLinux()) {
            set(WORKING_DIR, "/home/hung/Note");
            return "/home/hung/Note";
        } else {
            set(WORKING_DIR, "Working for window...");
            return "Working for window";
        }
    }
    
    public static void setWorkingDir(String dir) {
        set(WORKING_DIR, dir);
    }
    
    public static String getMetadatPath() {
       return get(WORKING_DIR) + "/metadata"; 
    }

    public static String getDBPath() {
        return get(DATABASE_PATH);
    }
    
    public static String getBookNotePath() {
        if (getDBPath() == null) {
            return "/home/hung/database/book/";
        } else {
            return getDBPath() + "/book/";            
        }
        
    }
    public static String getPaperNotePath() {
        if (getDBPath() == null) {
            return"/home/hung/database/paper/";
        } else {
            return getDBPath() + "/paper/";
        }
    }
    private static void saveMetadata(String str) {
        String path  = getMetadatPath();
        File metadata = new File(path);
        StringBuilder strBd = new StringBuilder();
        if (metadata.exists()) {
            BufferedReader reader = null;
            try {
                reader = Files.newReader(metadata, Charset.forName("UTF-8"));
                String strLine = "";
                while ((strLine = reader.readLine()) != null) {
                    strBd.append(strLine + "\n"); 
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                Closeables.closeQuietly(reader);
            }
            
        }
        strBd.append(str);
        BufferedWriter writer = null;
        try {
            writer = Files.newWriter(metadata, Charset.forName("UTF-8"));
            writer.write(strBd.toString());
        }catch (IOException e) {
            e.printStackTrace();
        } finally {
            Closeables.closeQuietly(writer);
        }
    }
    private static void readMetadata() {
        String path = getMetadatPath();
        BufferedReader reader = null;
        try {
            reader = Files.newReader(new File(path), Charset.forName("UTF-8"));
            String strLine;
            while ((strLine = reader.readLine()) != null) {
                String[] strs = strLine.split("::");
                set(strs[0], strs[1]);
            }
        }catch (IOException e) {
            e.printStackTrace();
        }finally {
            Closeables.closeQuietly(reader);
        }
    }
    public static void saveContext() throws IOException {
        BufferedWriter bw = Files.newWriter(new File(getMetadatPath()), Charset.forName("UTF-8"));
        bw.write(WORKING_DIR + "," + get(WORKING_DIR));
        bw.write(DATABASE_PATH + "," + getDBPath());
        Closeables.closeQuietly(bw);
    }
    public static String getUserName() {
        return get(USER_NAME);
    }
    public static String getPWD() {
        return get(PWD);
    }
    
}
